package com.example.demo.service.impl;

import com.example.demo.service.CacheService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @Author:Samson
 * @Description:
 * @Date:Created in 2017/6/2.
 */
@Service("cacheService")
public class CacheServiceImpl implements CacheService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private JedisConnectionFactory redisConnectionFactory;

    @Override
    public void saveRank(String userId, String rankList) {
        redisTemplate.opsForValue().set(userId,rankList);
    }

    @Override
    public String selectRank(String userId) {
        String str = redisTemplate.opsForValue().get(userId);
        return str;
    }

    /**
     * 获取存储的视频路径
     *
     * @param videoId
     * @return
     */
    @Override
    public String selectVideoId(String videoId) {
        String str = redisTemplate.opsForValue().get(videoId);
        return str;
    }

    /**
     * 切换数据库
     *
     * @param index
     * @return
     */
    @Override
    public CacheService selectDB(int index) {
        redisConnectionFactory.setDatabase(index);
        return this;
    }

    @Override
    public String selectValueByPhone(String phone) {
        return redisTemplate.opsForValue().get(phone);
    }

    @Override
    public void saveToken(String userId, String token) {
        redisTemplate.opsForValue().set(userId,token);
    }

    //2.1.4加上过期时间
    @Override
    public void setUserToken(String userId, String token) {
        redisTemplate.opsForValue().set(userId,token);
        redisTemplate.expire(userId, 10, TimeUnit.DAYS);
    }

    @Override
    public Long selectUserCacheTime(String userId) {
         return redisTemplate.getExpire(userId,TimeUnit.DAYS);
    }

    @Override
    public String selectUserCache(String userId) {
        return redisTemplate.opsForValue().get(userId);
    }

    @Override
    public void addPhone(String userId, String phone) {
        redisTemplate.opsForValue().set(userId,phone);
    }

}
